

import json
import os
import sys

from ErrorHandler import ErrorConfigFile

class Config:
    def __init__(self):
        self.home_user = os.environ.get('HOME')
        self.config = {}

        self.path_config_file = f"{self.home_user}/.config/arcalvus/arcalvus.json"
            
        if not os.path.isfile( self.path_config_file ):
            
            try:
                os.makedirs( f"{self.home_user}/.config/arcalvus" )
            except FileExistsError: ...
            
            self.CREATE_CONFIG()
            
        else:
            self._ReadConfig()
            self._CheckConfig()
    
    def _CheckConfig(self):
        key_list = [
                "CIPHER",
                "STORAGE_PATH",
                "GPG_ID"
                ]
                
        for json_config_key in self.config.keys():
            if not json_config_key in key_list:
                ErrorConfigFile(f"Invalid Key: {json_config_key}")
            
    def _ReadConfig(self):
        self.config = json.loads( open( self.path_config_file, 'r' ).read() )
            
    def _SaveStorage(self):
        open( self.path_config_file, "w" ).write( json.dumps( self.config, indent=4, ensure_ascii=False ) )
    
    def CREATE_CONFIG(self):
        self.config["GPG_ID"] = input("Enter GPG_ID: ")
        
        input_storage_path = input(f"Enter storage path \ndefault {self.home_user}/Documents/.arcalvus\n: ")
        
        if not input_storage_path:
            self.config["STORAGE_PATH"] = f"{self.home_user}/Documents/.arcalvus"
        else:
            self.config["STORAGE_PATH"] = str(input_storage_path)
            
        self._SaveStorage()
    
    def GET_GPG_ID(self):
        return self.config["GPG_ID"]
    
    def GET_STORAGE_PATH(self):
        return self.config["STORAGE_PATH"]
        
    def GET_CIPHER(self):
        try:
            return self.config["CIPHER"]
        except KeyError:
            return None


